package cn.source.config;

import com.wechat.pay.java.core.util.PemUtil;
import lombok.Getter;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Base64Utils;

import java.nio.charset.StandardCharsets;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.UUID;

/**
 * @author bomb
 */
@Configuration
@Getter
@Slf4j
public class WxPayV3Config {
    /**
     * 商户号
     */
    @Value("${payment.wechat.szymch-id}")
    private String mchId;

    /**
     * 商户API证书序列号
     */
    @Value("${payment.wechat.szyserial-number-v3}")
    private String mchSerialNo;

    /**
     * 商户私钥文件
     */
    @Value("${payment.wechat.szyprivate-key-v3}")
    private String privateKeyPath;

    /**
     * 商户公钥文件，2025年微信支付新要求
     */
    @Value("${payment.wechat.szypublic-key-v3}")
    private String publicKeyPath;

    public String getPrivateKeyPath() {
        return "c:/" + privateKeyPath;
    }

    public String getPublicKeyPath() {
        return "c:/" + publicKeyPath;
    }

    /**
     * 商户公钥ID
     */
    @Value("${payment.wechat.szypublic-id-v3}")
    private String szypublicId;

    /**
     * APIv3密钥
     */
    @Value("${payment.wechat.szyapi-key-v3}")
    private String apiV3Key;

    /**
     * 用户端APPID
     */
    @Value("${payment.wechat.wx_user_app_id}")
    private String userAppId;

    /**
     * 公众号APPID
     */
    @Value("${payment.wechat.szywx_js_appid}")
    private String jsAppId;

    /**
     * 公众号密钥
     */
    @Value("${payment.wechat.szywx_js_secret}")
    private String jsSecret;

//    @Resource
//    private MongoTemplate mongoTemplate;

    @SneakyThrows
    public String mpPaySign(String timeStamp, String nonceStr, String packageStr) {
        String signStr = jsAppId + "\n" + timeStamp + "\n" + nonceStr + "\n" + packageStr + "\n";
        //com.wechat.pay.java.core.util;
        PrivateKey privateKey = PemUtil.loadPrivateKeyFromPath(getPrivateKeyPath());
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(privateKey);
        sign.update(signStr.getBytes(StandardCharsets.UTF_8));
        return Base64Utils.encodeToString(sign.sign());
    }

    public String getTimeStamp() {
        return String.valueOf(System.currentTimeMillis() / 1000);
    }

    /**
     * 不超过32为随机字符串
     *
     * @return
     */
    public String getNonceStr() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

//    /**
//     * 更新用户 公众号 openid
//     *
//     * @param userId 用户id
//     * @param code   换取openidcode
//     */
//    public boolean updateUserMpOpenIdByCode(ObjectId userId, String code) {
//        log.info("用户 {} 绑定公众号openid {}", userId, code);
//        String mpOpenid = WxV3PayUtil.getJsOpenid(code);
//        return updateUserMpOpenId(userId,mpOpenid);
//    }
//
//    public boolean updateUserMpOpenId(ObjectId userId, String openId) {
//        log.info("用户 {} 绑定公众号openid {}", userId, openId);
//        if(StringUtils.hasText(openId)){
//            //移除原来的
//            mongoTemplate.updateMulti(Query.query(Criteria.where("wechat_mp_open_id").is(openId)),
//                    new Update().set("wechat_mp_open_id",null), UserEntity.class);
//            //更新
//            Update update = new Update();
//            update.set("wechat_mp_open_id", openId);
//            update.set(CommonDataEntity.UPDATED_NAME,new Date());
//            mongoTemplate.updateFirst(Query.query(Criteria.where(CommonDataEntity.DATA_ID).is(userId)), update, UserEntity.class);
//            return true;
//        }
//        return false;
//    }
}
